<?php
	function timedate()
	{
		if ( isset($_POST["date"]) && isset($_POST["time"])) {
			$date = explode("-",$_POST["date"]);
			$time = explode(":",$_POST["time"]);
			exec("/bin/date $date[1]$date[2]$time[0]$time[1]$date[0].$time[2] 2> /dev/null", $duh, $ret);
			if ($ret != 0) {
				error('time_notvalid');
			}
			else {
				$_SESSION["time"] = time();  // uppdaterar tid i session, vill ju inte slänga ut användare
				info('time_saved');
			}
		}
	}

	
	function net()
	{
		$filename = "/etc/network/interfaces";

	    // Windowsnät
	    // hostname + domän (idag samma som windowsnät)
	    	$error = false;
		$smblines = file('/etc/samba/smb.conf');
		$hostslines = file('/etc/hosts');
		$netbiosname = trim($_POST['netbiosname']);
		$workgroup = trim($_POST['workgroup']);
		if( preg_match('/^[a-z0-9-]*$/i', $netbiosname ) ) {
			$smblines = preg_replace('/^(\s*netbios name\s*=\s*).*$/', '$1'.$netbiosname, $smblines);
			$hostslines = preg_replace('/^(\s*127.0.0.1\s+).*$/', '$1'."localhost\t$netbiosname", $hostslines);
		}
		else {
			error('net_wrong_netbiosname');
			$error = true;
		}
		if( preg_match('/^[a-z0-9-]*$/i', $workgroup && $error == false ) ) {
			$smblines = preg_replace('/^(\s*workgroup\s*=\s*).*$/', '$1'.$workgroup, $smblines);
			$hostslines = preg_replace('/^(\s*127.0.1.1\s+).*$/', '$1'.$netbiosname.'.'.$workgroup."\t".$netbiosname, $hostslines);
		}
		else {
			error('net_wrong_workgroup');
			$error = true;
		}
		if( $error == false ) {
			//skriv i conffiler
			file_put_contents('/etc/samba/smb.conf', $smblines);
			file_put_contents('/etc/hosts', $hostslines);
			file_put_contents('/etc/hostname', $netbiosname);
			//kör eller starta om tjänster
			exec('PATH=/sbin:"${PATH}"; /etc/init.d/hostname.sh start > /dev/null 2> /dev/null');
			exec('PATH=/sbin:"${PATH}"; /etc/init.d/samba restart > /dev/null 2> /dev/null &');
			exec('PATH=/sbin:"${PATH}"; /etc/init.d/postfix restart > /dev/null 2> /dev/null &');
		}

		
	    // Avancerat
		$error = false;
		if( isset($_POST['dhcp']) )
			$dhcp = $_POST['dhcp'];
		else {
			$ip = trim($_POST['ip']);
			$netmask = trim($_POST['netmask']);
			$defaultgw = trim($_POST['defaultgw']);
			$dns1 = trim($_POST['dns1']);
			$dns2 = trim($_POST['dns2']);

			//Kontrollerar adresserna
			$num="(25[0-5]|2[0-4]\d|[01]?\d\d|\d)";
			if (!preg_match("/^$num\\.$num\\.$num\\.$num$/", $ip)) {
				error('net_wrong_ip');
				$error = true;
			}
			if (!preg_match("/^$num\\.$num\\.$num\\.$num$/", $netmask)) {
				error('net_wrong_netmask');
				$error = true;
			}
			if (!preg_match("/^$num\\.$num\\.$num\\.$num$/", $defaultgw)) {
				error('net_wrong_gateway');
				$error = true;
			}
			if ( $dns1!="" && !preg_match("/^$num\\.$num\\.$num\\.$num$/", $dns1) ) {
				error('net_wrong_dns');
				$error = true;
			}
			if ( $dns2!="" && !preg_match("/^$num\\.$num\\.$num\\.$num$/", $dns2) ) {
				error('net_wrong_dns');
				$error = true;
			}
		}

	     //Spara uppgifter om ej fel
		if( !$error ) {
			//spara nätverksinställningar
			$buff = "auto lo eth0\n";
			$buff.= "iface lo inet loopback\n";
			if ( isset($dhcp) )
				$buff.= "iface eth0 inet dhcp\n";
			else {
				$buff.= "iface eth0 inet static\n";
				$buff.= "     address $ip\n";
				$buff.= "     netmask $netmask\n";
				$buff.= "     gateway $defaultgw\n";
			}
			if (!$handle = fopen($filename, 'w')) {
				error('file_open_conffile');
				exit;
			}
			if (fwrite($handle, $buff) === FALSE) {
				error('file_write_conffile');
				exit;
			}
			fclose($handle);

			//spara dns-inställningar
			$resolv_file = file('/etc/resolv.conf');
			if (!$handle = fopen('/etc/resolv.conf', 'w')) {
                                error('file_open_conffile');
                                exit;
                        }
			foreach( $resolv_file AS $line ) {
				if( trim($line) != "" && !preg_match('/^nameserver /', $line) ) {
					if (fwrite($handle, $line) === FALSE) {
						error('file_write_conffile');
						exit;
					}
				}
			}
			$buff = "";
			if( $dns1 != "" )
				$buff .= "\nnameserver ".$dns1;
			if( $dns2 != "" )
				$buff .= "\nnameserver ".$dns2;
			if (fwrite($handle, $buff) === FALSE) {
				error('file_write_conffile');
				exit;
			}
			fclose($handle);

			//aktivera de nya inställningarna
			exec('/sbin/ifdown eth0 > /dev/null 2> /dev/null; /sbin/ifup eth0 > /dev/null 2> /dev/null &');
		}
	}
		

	function upgrade()
	{
		if( $_POST['b_unow'] ) {
			//putenv ( 'PATH='.getenv("PATH").':/sbin:/usr/sbin:/usr/local/sbin' ); // thttpd har rensat bort dessa
			shell_exec("nohup ../services/settings/upgrade >> /var/log/apt 2>> /var/log/apt &");
			info('update_started');
		}
		else {
			if ( !$_POST["autoupdate"]) {
				@unlink("/etc/cron.d/upgrade");
				info('saved');
			}
			else if ($_POST["hour"] && $_POST["day"]) {
				$str = "0 ".$_POST["hour"]." * * ". $_POST["day"] ." root ../services/settings/upgrade >> /var/log/apt 2>> /var/log/apt\n";
				file_put_contents("/etc/cron.d/upgrade",$str);
				info('saved');
			}
		}
	}

	
	function password()
	{
		$LOGIN_FILE = '../login';
		
		//$old_username = $_POST['ousername'];
		$old_passwd = $_POST['opasswd'];
		//$new_username = $_POST['nusername'];
		$new_passwd1 = $_POST['npasswd1'];
		$new_passwd2 = $_POST['npasswd2'];

		if( !auth_pass( 'root', $old_passwd ) ) {
			error('password_deny_old');
		} else if( $new_passwd1 != $new_passwd2 ) {
			error('password_not_same');
		} else if( /*$new_username == "" ||*/ $new_passwd1 == "" ) {
			error('password_empty');
		} else {
			if( !save_pass( 'root', $new_passwd1 ) )
				error('unknown');
			else
				info('password_saved');
		}
        }


	function adminmail()
	{
		require "../inc/rwINIfile.php";

		global $POSTCONF;
		global $ADMINMAILCONF;

		$settings = readConf( $POSTCONF );

		$email = trim($_POST['adminmail']);
		if( isset($_POST['relayhost']) )
			$settings["relayhost"] = $_POST["relayhost"];
		
		file_put_contents( $ADMINMAILCONF, $email."\n" );
		writeConf($POSTCONF, $settings);
		exec("/etc/init.d/postfix restart &");
	}


	function power()
	{
		if( isset($_POST['b_reboot']) ) {
			info('power_reboot');
			exec('/sbin/reboot');
		} else if( isset($_POST['b_halt']) ) {
			info('power_halt');
			exec('/sbin/halt');
		}
	}	


	switch( $_GET['t'] ) {
	case 'timedate':
		timedate();
		break;
	case 'net':
		net();
		break;
	case 'upgrade':
		upgrade();
		break;
	case 'admin':
		if( isset($_POST['opasswd']) && $_POST['opasswd'] != "" )
			password();
		if( isset($_POST['adminmail']) )
			adminmail();
		if( isset($_POST['testmail']) ) {
			sendmail('Ett testmail', 'Det här är ett testmail efterfrågat från Uggla.');
		}
		break;
	case 'power':
		power();
		break;
	default:
		timedate();
		break;
	}
?>
